package cn.wolfcode.service.impl;

import cn.wolfcode.domain.Employee;
import cn.wolfcode.exception.LogincException;
import cn.wolfcode.mapper.EmployeeMapper;
import cn.wolfcode.qo.EmployeeQueryObject;
import cn.wolfcode.service.IEmployeeService;
import cn.wolfcode.util.UserContext;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;

@Service
@Transactional//事务
public class EmployeeServiceImpl implements IEmployeeService {
    @Autowired
    private EmployeeMapper employeeMapper;

    @Override
    public void delete(Long id) {
        employeeMapper.deleteByPrimaryKey(id);
    }

    @Override
    public void save(Employee employee, Long[] ids) {
        //对密码进行加密
        Md5Hash md5Hash = new Md5Hash(employee.getPassword(), employee.getName(), 2);
        //加密后转为字符串设置进密码中
        employee.setPassword(md5Hash.toString());
        //先保存之后employee就会有id
        employeeMapper.insert(employee);
        //关联关系,把角色ID加入到角色中间表
        if (ids != null && ids.length > 0) {
            for (Long roleId : ids) {
                employeeMapper.insertReation(employee.getId(), roleId);
            }
        }
    }

    @Override
    public Employee get(Long id) {
        return employeeMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Employee> listAll() {
        return employeeMapper.selectAll();
    }

    @Override
    public void update(Employee employee, Long[] ids) {
        employeeMapper.updateByPrimaryKey(employee);
        //删除关系
        employeeMapper.deleteRelation(employee.getId());
        //关联关系,把角色ID加入到角色中间表
        if (ids != null && ids.length > 0) {
            for (Long roleId : ids) {
                employeeMapper.insertReation(employee.getId(), roleId);
            }
        }
    }

    @Override
    public PageInfo<Employee> query(EmployeeQueryObject qo) {
        /*//查询数量
        int count = employeeMapper.selectForCount(qo);
        System.out.println("查询数量==="+count);

        if (count == 0) {
            return new PageResult<>(qo.getCurrentPage(),
                    qo.getPageSize(), count, Collections.emptyList());
        }////Collections.emptyList(),返回一个空的集合

        List<Employee> employees = employeeMapper.selectForList(qo);
        return new PageResult<>(qo.getCurrentPage(),
                qo.getPageSize(), count, employees);*/

        //告诉插件要开始分页了,传入当前页,每页显示数据
        PageHelper.startPage(qo.getCurrentPage(), qo.getPageSize());
        List<Employee> employees = employeeMapper.selectForList(qo);
        return new PageInfo<>(employees);
    }

 /*   //登录
    public Employee login(String username, String password) {
        if (!StringUtils.hasText(username)) {
            throw new LogincException("用户名不能为空!");
        }
        if (!StringUtils.hasText(password)) {
            throw new LogincException("密码不能为空");
        }
        //判断用户和密码是否存在数据库
        Employee employee = employeeMapper.selectByUsernameAndPassword(username, password);
        if (employee == null) {
            throw new LogincException("用户名或密码错误");
        }
        //禁用状态,不允许登录
        if(!employee.isStatus()){
            throw new LogincException("账号已被禁用!");

        }
        return employee;

    }*/

    @Override
    public void resetPwdPage(String newPassword, Long id) {
        employeeMapper.resetPwdPage(newPassword, id);
    }

    //修改密码
    @Override
    public void updatePwdPage(String oldPassword, String newPassword, Long id) {
        Employee employee = UserContext.getCurrentUser();
        //加密
        Md5Hash md5Hash = new Md5Hash(oldPassword, employee.getName(), 2);
        //加密后转为字符串设置进用户输进来的密码中
        String password = md5Hash.toString();
        if (!employee.getPassword().equals(password)) {
            throw new LogincException("密码不正确");
        }
        employeeMapper.updatePwdPage(oldPassword, newPassword, id);
    }

    //批量删除
    @Override
    public void batchDelete(Long[] ids) {
        employeeMapper.batchDelete(ids);
    }

    //远程验证
    //验证用户名是否存在
    @Override
    public Employee selectByName(String name) {
        Employee employee = employeeMapper.selectByName(name);
        return employee;
    }

    //导出
    @Override
    public Workbook exportXls() {
        //查询所有员工
        List<Employee> employees = employeeMapper.selectAll();
        //使用poi创建一个excel
        HSSFWorkbook wb = new HSSFWorkbook();
        //创建excel中的表
        HSSFSheet sheet = wb.createSheet("员工通讯录");
        //创建标题数据,从0开始, 创建单元格,写入内容到单元格
        HSSFRow row = sheet.createRow(0);
        row.createCell(0).setCellValue("姓名");
        row.createCell(1).setCellValue("邮箱");
        row.createCell(2).setCellValue("年龄");
        //遍历获取员工数据
        for (int i = 0; i < employees.size(); i++) {
            Employee employee = employees.get(i);
            //给每个员工创建一行数据
            row = sheet.createRow(i + 1);
            //创建单元格,写入内容到单元格
            row.createCell(0).setCellValue(employee.getName());
            row.createCell(1).setCellValue(employee.getEmail());
            row.createCell(2).setCellValue(employee.getAge());
        }
        return wb;
    }

    //导入
    @Override
    public void importXls(MultipartFile file) throws IOException {
        //读取上传的文件,并且封装为一个Workbook对象
        HSSFWorkbook wb = new HSSFWorkbook(file.getInputStream());
        //读取第0张sheet表
        HSSFSheet sheet = wb.getSheetAt(0);
        //获取最后一行的索引
        int lastRowNum = sheet.getLastRowNum();
        //标题行不用读,lastRowNum是代表索引,需要使用=
        for (int i = 1; i < lastRowNum; i++) {
            //获取每一行数据
            HSSFRow row = sheet.getRow(i);
            Employee employee = new Employee();
            //判断空值问题,用户名或邮箱其中一个为空就不再读取(看需求添加)
            if (row.getCell(0)==null || row.getCell(1)==null){
                break;
            }
            employee.setName(row.getCell(0).getStringCellValue());
            employee.setEmail(row.getCell(1).getStringCellValue());
            //判断单元格格式
            HSSFCell cell = row.getCell(2);
            if (cell.getCellType() == CellType.NUMERIC){//作为数据单元格读取
                int age = ((int)cell.getNumericCellValue());
                //年龄限制
                if (age<18 || age >60){
                    throw new LogincException("第" + i + "行数据有问题,年龄范围在18~60之间");
                }
                employee.setAge(age);
            }else {
                employee.setAge(Integer.valueOf(cell.getStringCellValue()));
            }

            employeeMapper.insert(employee);
        }
    }

    //禁用/恢复账号功能
    @Override
    public void updateStatus(Long id, int status) {
        employeeMapper.updateStatus(id,status);
    }

    @Override
    public List<Employee> selectByRoleSn(String... sns) {
        return employeeMapper.selectByRoleSn(sns);
    }


}
